using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-班次管理
    /// </summary>
    public class ShiftController : Controller
    {
        private readonly IShiftService _shiftService;

        public ShiftController(IShiftService shiftService)
        {
            _shiftService = shiftService;
        }

        /// <summary>
        /// 班次查询页面
        /// </summary>
        /// <returns></returns>
        public IActionResult ShiftQuery()
        {
            return View();
        }

        /// <summary>
        /// 获取班次分页列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetShiftPageList(int page = 1, int limit = 10)
        {
            try
            {
                var result = await _shiftService.GetShiftPageListAsync(page, limit);
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 1,
                    msg = $"查询失败：{ex.Message}",
                    count = 0,
                    data = new object[] { }
                });
            }
        }

        /// <summary>
        /// 测试数据接收
        /// </summary>
        /// <param name="rawData">原始数据</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult TestShiftData([FromBody] object rawData)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"接收到的原始数据: {rawData}");
                return Json(new { success = true, message = "数据接收成功", data = rawData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 添加班次
        /// </summary>
        /// <param name="shiftCreateDto">班次数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddShift([FromBody] JsonElement shiftData)
        {
            try
            {
                // 调试信息
                System.Diagnostics.Debug.WriteLine($"接收到的原始数据: {shiftData}");
                
                // 手动提取数据，正确处理JsonElement
                string shiftName = null;
                string startTime = null;
                string endTime = null;

                if (shiftData.TryGetProperty("shiftName", out var shiftNameElement))
                {
                    shiftName = shiftNameElement.GetString();
                }
                if (shiftData.TryGetProperty("startTime", out var startTimeElement))
                {
                    startTime = startTimeElement.GetString();
                }
                if (shiftData.TryGetProperty("endTime", out var endTimeElement))
                {
                    endTime = endTimeElement.GetString();
                }

                System.Diagnostics.Debug.WriteLine($"提取的数据: ShiftName={shiftName}, StartTime={startTime}, EndTime={endTime}");

                if (string.IsNullOrEmpty(shiftName))
                {
                    return Json(new { success = false, message = "班次名称不能为空" });
                }
                if (string.IsNullOrEmpty(startTime))
                {
                    return Json(new { success = false, message = "开始时间不能为空" });
                }
                if (string.IsNullOrEmpty(endTime))
                {
                    return Json(new { success = false, message = "结束时间不能为空" });
                }

                // 创建DTO对象
                var shiftCreateDto = new ShiftCreateDTO
                {
                    ShiftName = shiftName,
                    StartTime = startTime,
                    EndTime = endTime
                };

                var result = await _shiftService.AddShiftAsync(shiftCreateDto);
                if (result)
                {
                    return Json(new { success = true, message = "添加班次成功" });
                }
                else
                {
                    return Json(new { success = false, message = "添加班次失败" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"添加班次异常: {ex}");
                return Json(new { success = false, message = $"添加失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取班次详情
        /// </summary>
        /// <param name="id">班次ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetShiftById(int id)
        {
            try
            {
                var result = await _shiftService.GetShiftByIdAsync(id);
                if (result != null)
                {
                    return Json(new { success = true, data = result });
                }
                else
                {
                    return Json(new { success = false, message = "班次不存在" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取详情失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新班次
        /// </summary>
        /// <param name="shiftUpdateDto">班次数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateShift([FromBody] JsonElement shiftData)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"更新班次接收到的原始数据: {shiftData}");
                
                // 手动提取数据，正确处理JsonElement
                string idStr = null;
                string shiftName = null;
                string startTime = null;
                string endTime = null;

                if (shiftData.TryGetProperty("id", out var idElement))
                {
                    idStr = idElement.ToString();
                }
                if (shiftData.TryGetProperty("shiftName", out var shiftNameElement))
                {
                    shiftName = shiftNameElement.GetString();
                }
                if (shiftData.TryGetProperty("startTime", out var startTimeElement))
                {
                    startTime = startTimeElement.GetString();
                }
                if (shiftData.TryGetProperty("endTime", out var endTimeElement))
                {
                    endTime = endTimeElement.GetString();
                }

                if (!int.TryParse(idStr, out int id))
                {
                    return Json(new { success = false, message = "班次ID无效" });
                }
                if (string.IsNullOrEmpty(shiftName))
                {
                    return Json(new { success = false, message = "班次名称不能为空" });
                }
                if (string.IsNullOrEmpty(startTime))
                {
                    return Json(new { success = false, message = "开始时间不能为空" });
                }
                if (string.IsNullOrEmpty(endTime))
                {
                    return Json(new { success = false, message = "结束时间不能为空" });
                }

                // 创建DTO对象
                var shiftUpdateDto = new ShiftUpdateDTO
                {
                    Id = id,
                    ShiftName = shiftName,
                    StartTime = startTime,
                    EndTime = endTime
                };

                var result = await _shiftService.UpdateShiftAsync(shiftUpdateDto);
                if (result)
                {
                    return Json(new { success = true, message = "更新班次成功" });
                }
                else
                {
                    return Json(new { success = false, message = "更新班次失败" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新班次异常: {ex}");
                return Json(new { success = false, message = $"更新失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 删除班次
        /// </summary>
        /// <param name="id">班次ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteShift(int id)
        {
            try
            {
                var result = await _shiftService.DeleteShiftAsync(id);
                if (result)
                {
                    return Json(new { success = true, message = "删除班次成功" });
                }
                else
                {
                    return Json(new { success = false, message = "删除班次失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }
    }
} 